package com.album.utils.down;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.graphics.drawable.Drawable; 
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoaders {
	
	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

	public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				return softReference.get();
			}
		}
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				callback.imageLoaded((Drawable) msg.obj, imageUrl);
			}
		};
		new Thread() {
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				handler.sendMessage(handler.obtainMessage(0, drawable));
			};
		}.start();
		return null;
	}

	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			return ImageUtil.getDrawableFromUrl(imageUrl);
		} catch (OutOfMemoryError e) {
			return null;
		}
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
	public void clearDataSource(){
    	try {
    		if(imageCache!=null && imageCache.size()>0){
        		Iterator<java.util.Map.Entry<String, SoftReference<Drawable>>> it = imageCache.entrySet().iterator();
        		while(it.hasNext()){
        			Map.Entry<String, SoftReference<Drawable>> entry = (Entry<String, SoftReference<Drawable>>) it.next().getValue();
        			SoftReference<Drawable> sBitmap = entry.getValue();
        			Drawable bitmap = sBitmap.get();
        			
//        			if(bitmap!=null && bitmap.isRecycled()){
//        				bitmap.recycle(); 
//        				bitmap=null;
//        			}
        			sBitmap.clear();
        			sBitmap=null;
        			entry=null;
        		}
        		imageCache.clear();
        	}
		} catch (Exception e) { e.printStackTrace();}
    }
}
